Writing Python Scripts
Python is one of the most popular coding languages used today, and implementing a Python script within Vulcan can greatly enhance the speed of many tasks. A script can be written to execute a single task, or it can be expanded to initiate a complete workflow encompassing multiple tasks.
The keys to using Python in Vulcan are the Vulcan Class Libraries. These contain all the specialised functions used to manipulate Vulcan objects.
Use the maptek.vulcan_gui.gfx
class modules to provide functionality for window listing and setting, view control, and view feature control.
Use the maptek.crypt
class modules to run encrypted scripts or to compile scripts to an ecrypted format with a supplied private key.
Note: There are currently over 900 functions listed in the Vulcan Class Modules. For a complete list click here.
Important: Any Python script can be run from within Vulcan. This means that all of the Python libraries can be accessed by using the standard Python protocols to import a class library. However, a script using Vulcan class libraries can only be run from within Vulcan and are only supported while running from within that environment. Customised setups are at your own discretion.
Python Basics
Creating and saving Python scripts
Python scripts can be written using any text editor. You do not need an advanced compiler.
Python files can be saved like any file in Windows. When saving an untitled file as a Python file, manually enter the py extension using the format <filename>.py
.
Note: Some editors may save files with a txt
extension by default, resulting in a file named <filename>.py.txt
. To avoid this format, select All types or Python file in the Save as type drop-down list before clicking Save. You can rename a file with an incorrect extension in Windows Explorer.
Comments
Writing comments in the code is good practice. Comments can clarify a section of code and provide documentation for other users.
Single-line comments are created by beginning a line with the hash character (#
) and are automatically terminated at the end of the line.
# This is a comment. print("Hello World")
Multi-line comments are created by surrounding the comment block with three quotations marks at the beginning and end. Both single quotes (')
and double quotes (")
can be used.
''' This is a longer comment. It has multiple lines. It can be used for headings and instructions.''' print("Hello World")
Variables
Variables are names that refer to a value. More specifically, they are named assignments between data values and their locations in computer memory.
Variable names must begin with an underscore or letter. A variable name can be as long as you want and made of alphanumeric characters or underscores, but not spaces or special characters.
Tip: Try to use variable names that are descriptive to make your code easier to read and debug. For example, the purpose for a variable named 'cd'
is not very clear. However, you could probably guess what a variable named 'current_day_of_the_week'
is used for.
To assign a value to a variable, enter the variable name on the left of the assignment operator (=
) and the value on the right. The value can be an expression. In this example, Python evaluates the expression 2 + 2
on the right hand side before assigning the calculated value to the variable total
.
total = 2 + 2
A variable can be reassigned to a new value. Upon reassignment, the old value is lost.
The data type of a value or variable defines what kind of operations can be performed on it. Python sets the variable type based on the assigned value and it does not need to be declared in advance. In many languages, the variable type is constant throughout the entire program. As there is no such restriction in Python, the following code is valid:
day = "Thursday" day = "Friday" day = 21
In this example, having two different variables named day_of_week
and day_of_month
would reduce confusion.
Note: Changing variable types in a script is not common practice as it is easy to make mistakes. Instead of mixing data types, define multiple variables to ensure that the meaning of the code remains clear.
There are some Python keywords such as if
and else
that cannot be used as variable names. also, do not declare variables using the same name as any function calls in your code.
extent_list = tri.extent()
is okay to use because the variable name extent_list
differs from the function call extent()
.
extent = tri.extent()
is not okay because the variable name extent
is the same as function call extent()
.
Operators
Python has most standard operators, similar to those seen in tools like Microsoft Excel. The following table gives examples of commonly used operators available in Python.
Numeric Operators by Ascending Priority
Operator | Calculation | Example | Return |
---|---|---|---|
+
|
Addition | 34 + 2.5
|
36.5
|
-
|
Subtraction | 2 - 36
|
-34
|
*
|
Multiplication | 123456 * 5
|
617280
|
/
|
Float Division | 617 / 3
|
205.666667
|
//
|
Integer Division | 617 // 3
|
205
|
%
|
Modulus | 617 % 3
|
2
|
**
|
Exponentiation | 5 ** 3
|
125
|
Built-in Numeric Functions
Function | Return |
---|---|
abs(x)
|
Absolute value of x |
int(x)
|
x converted to integer |
float(x)
|
x converted to floating point |
divmod(x, y)
|
(x // y, x % y) |
pow(x, y)
|
x to the power of y |
round(x, n)
|
x rounded to n digits |
Characters and Strings
A character is a single letter, number, space, or symbol, denoted with single or double quotes. A string is made up of one or more characters and is also denoted with single or double quotes. Its data type is str
.
Any values enclosed in quotes belong to the data type string. The equation 2 + 2
evaluates to 4
, but the equation ‘2’ + ‘2’
evaluates to ‘22’
because the quote enclosed characters are interpreted as strings.
Boolean Values
A Boolean value is either True
or False
. Its Python type is bool
.
Statements
Statements control the execution of code in a block. Each block limits the scope of a portion of code.
Python uses indentation to mark blocks of code. All lines indented by the same number of spaces belong to the same block. Code blocks can contain any number of statements.
In the following example, the two address print statements are in the same code block. When the if
statement is true, both print statements will be executed. The string 'Maptek Delivery'
is outside of the code block. It will be printed regardless of whether the if
statement is True
or False
.
if x == 'DENVER': print(14143 Denver West Parkway, Suite 200') print('Golden, CO 80401') print('Maptek Delivery')
Tabs and spaces cannot be mixed for indentation. Most editors support translation of tabs into spaces. When the tab key is pushed, the editor inserts a set number of spaces.
Conditional Statements
Conditional statements perform a task if a certain condition is met. The most common conditional statement is the if
statement.
The if
statement will evaluate if the entered expression evaluates as True
or False
. If the return value is not explicitly a Boolean, the values 0
and None
will evaluate as False
. All other values will evaluate as True
.
The if
statement always ends with a colon. Omitting the colon results in a SyntaxError. Almost every line of code that leads into a new code block will end with a colon.
The following example evaluates grades for destination.
cutoff = 1 grade = 0.6 if grade < cutoff: print('waste') else: print('ore')
Comparison Operators
Comparisons operators compare the values on either side of the operator and return a Boolean value indicating the relation between them.
A list of commonly used comparison operators follows.
Operator | Comparison | Example | Return |
---|---|---|---|
==
|
Equality | 5 == 3
|
False
|
!=
|
Inequality | 5 != 3
|
True
|
>
|
Greater than | 5 > 3
|
True
|
>=
|
Greater than or equal | 5 >= 3
|
True
|
<
|
Less than | 5 < 3
|
False
|
<=
|
Less than or equals | 5 <= 3
|
False
|
Note: The equality operator (==
) is different from the assignment operator (=
). Attempting to use the assignment operator in a comparison results in a SyntaxError.
Logical Operators
Logical operators allow testing of two or more conditions at one time. The logical operators in Python are and
, or
, and not
.
A set of statements joined by and
is True
if and only if all statements prove true. A set of statements joined by or
is True
if any of the statements prove true. The not
operator negates the Boolean value of a statement.
test_val = 40 test_strs = ['apple;, 'banana', 'carrot'] if test_val < 50 and len(test_strs) == 2: print('test 1 passed') if test_val < 50 or len(test_strs) == 2: print('test 2 passed') if not test_val >= 50: print('test 3 passed')
When using logical operators in an if statement, order matters! The conditions are evaluated from left to right. For statements joined by or
, if the first condition is true
, the second condition is skipped.
else and elif
When using if
statements, else
and elif
statements allow a statement to evaluate to more than two possibilities. This makes the statement more robust in complex scenarios.
In the following example, each condition evaluates in order. If the first if
condition evaluates as False
, the second condition in the elif
statement is evaluated. If the elif
condition is False
, the else
actions always perform.
mill_cutoff = 1.2 heap_cutoff+ 0.8 destination = None grade = 1.5 if grade > mill_cutoff: destination = 'MILL' elif grade > heap_cutoff: destination = 'HEAP' else: destination = 'DUMP' print(destination)
Nested if statements
More complex scenarios may call for multiple if statements. Note that the following example using nested if
statements returns the same results as the elif
example.
mill_cutoff = 1.2 heap_cutoff+ 0.8 grade = 1.5 if grade > mill_cutoff: destination = 'MILL' else: if grade > heap_cutoff: destination = 'HEAP' else: destination = 'DUMP' print(destination)
Ordering is very important when using nested if
or elif
statements. In the example above, the destination is the mill because the provided grade value of 1.5 is above the cutoff for the mill of 1.2.
In the following example, conditions are ordered differently. In this case, all material will route to the heap since the first condition proves true and ends the statement.
mill_cutoff = 1.2 heap_cutoff+ 0.8 grade = 1.5 if grade > heap_cutoff: destination = 'HEAP' elif grade > mill_cutoff: destination = 'MILL' else: destination = 'DUMP' print(destination)
Loop statements
Loop statements repeat a code block multiple times. Python has two types of loops: for
loops and while
loops.
for loops
A for
loop processes each item in a set. The variable in the for statement is called the loop variable. Any variable name can be chosen. During each iteration of the loop, the loop variable is assigned the next value in a range, list or other data structure with the keyword in.
The body of the loop is an indented block of code. All the statements within the block are performed during each iteration of the loop.
for i in range(1, 10): print(i) j = i + 10 print(j) for state in ['Colorado', 'Nevada', 'Oregon', 'Utah']: print(state)
The function range(a, b)
creates a list of integers from a
to b – 1
.
In the example, the for
loop comes to the first item in the list, the integer 1
, and assigns the value to the loop variable i
. All the statements in the body are executed with i
equal to 1
. At the end of the loop, the program returns to the for
statement to iterate the list and check for remaining items. In the example, the iteration updates the loop variable from 1
to the next item, 2
. All the statements are executed with i
equal to 2
. This iteration repeats through the last item in the list, the integer 9
. After 9
, there are no more items in the list and the for
loop terminates.
while loops
A while
loop processes only while a condition is True
. The loop stops when the condition evaluates as False
. In the following example, the loop repeats until the counter value reaches 10
. The values 1
through 9
will be printed.
The body of the loop should change the value of the loop iterator so that eventually the condition becomes false. It is easy to forget the iterator, which is often the last line in the loop. The location of the iterator provides additional ability to customize how and when tasks are performed inside the loop.
counter = 0 while counter > 10: print(counter) counter += 1
Stopping loops
It may be necessary to modify the behaviour of a loop within the body to either end the loop operation entirely or to skip to the next iteration.
The break
statement exits a loop when an external condition is met, usually inside an if
statement. Any remaining iterations of the loop are also terminated and the statement following the loop block is executed.
numbers = [12, 16, 17, 24, 29] # using 'break' for i in numbers: if i % 2 == 1: break print(i) # Result: >>> 12 >>> 16
The continue
statement skips the remainder of a specific iteration of a loop. The loop will invoke the iterator and move to the next iteration.
numbers = [12, 16, 17, 24, 29] # using 'break' for i in numbers: if i % 2 == 1: continue print(i) # Result: >>> 12 >>> 16 >>> 24
Reading and writing data
The open
command allows Python access a file so that it can either read from a file or write to the file. The default open
mode for Python is 'r'
(read). However, you will not be able to write data to a file unless it is opened in 'write'
mode.
Access modes
-
Read Only
('r')
-
Read and Write
('r+')
-
Write Only
('w')
-
Write and Read
('w+')
-
Append Only
('a')
-
Append and Read
('a+')
Tip: While not absolutely necessary to declare the access mode when opening a file, it is always a good practice to do so.
filename = 'maptek.txt' fh = open(filename, 'r') for line in fh: print(line) fh.close()
Opening a file using the with
statement
The advantage to using the with
statement to open your file is that the file will be updated and saved automatically when the script exits the statement.
Both of these code snippets will have the same results, but Ex. 2 will need to call the save()
function.
# Create a new triangulation. from pathlib import Path from maptek import vulcan new_tri = 'new2.00t' triPath = Path(new_tri) if triPath.exists(): print (f"Triangulation file {triPath} already exists.") exit() else: # Ex 1 with vulcan.triangulation(new_tri, 'w') as tri: tri.add_node(78042.0, 5187.0, 78.0) tri.add_node(78033.0, 5164.0, 87.0) tri.add_node(78059.0, 5165.0, 70.0) tri.add_face(0,1,2) print(f"{new_tri} was created.") #Ex 2 tri = vulcan.triangulation(new_tri, 'w') tri.add_node(78042.0, 5187.0, 78.0) tri.add_node(78033.0, 5164.0, 87.0) tri.add_node(78059.0, 5165.0, 70.0) tri.add_face(0,1,2) tri.save() print(f"{new_tri} was created.")
Note: The filename variable can be assigned without using a path if the input file and the Python script are in the same directory. If the file is located outside of your current working directory, then you will need to include the path along with the name of the file.
Example scripts
We have provided example scripts that can be used just as they are written or as a starting point for your own scripts. Additional example scripts can be found on the pages detailing the various class modules.
To use the example scripts, you will need to change the names of any input files or objects to match the names of the files or objects you are trying to edit. For example, in the script shown below, you might need to change the name of the input triangulation to match the one you are working with.
# Get the triangulation extent and return as a list from maptek import vulcan input_tri = 'topo.00t' # input triangulation with vulcan.triangulation(input_tri) as tri: # Open triangulation to get information extent_list = tri.extent() # Get extent list print(f"{extent_list}") # print the value of 'extent_list' to the screen
Like the script above, the scripts used in this documentation are written using the following format:
-
Include a brief comment stating the purpose/function of the script
- Import any necessary class module libraries
-
Declare any variables
-
Write main section of code